/**
 * 
 */
package cn.ad.server.web.servlet.v2;

import cn.ad.server.common.utils.IPUtils;
import cn.ad.server.common.utils.SpringContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 提供restful方式路径处理
 * @author Wu Chengjun
 */
//@WebFilter(filterName="ResutPathFilter", urlPatterns="/v2/*")
public class RestPathFilter implements Filter{
	
	/**
	 * 初始化配置参数-- http代理接口Spring 注入名称
	 */
	public static final String PARAM_PROXY_BEAN_NAME = "proxy-bean-name";
	
	private static Logger LOGGER = LoggerFactory.getLogger(RestPathFilter.class);
	
	/**
	 * http请求处理代理接口
	 */
	private HttpServletProxy servletProxy;
	
	/**
	 * 代理接口实现Bean的名称
	 */
	private String servletProxyBeanName;

	/**
	 * 
	 */
	public RestPathFilter() {
		servletProxy = SpringContextUtils.getBean(HttpServletProxy.class);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//HttpServletProxy代理接口spring 配置beanID
		String beanname = filterConfig.getInitParameter(PARAM_PROXY_BEAN_NAME);
		if(StringUtils.isNoneEmpty(beanname)){
			this.servletProxyBeanName = beanname;
		}else{
			throw new ServletException("the parameter[servletproxy-BeanID] of filter is null");
		}
	}
	
	private HttpServletProxy getServletProxy() throws ServletException{
		if(servletProxy != null){
			return servletProxy;
		}else{
			servletProxy =  (HttpServletProxy) SpringContextUtils.getBean(servletProxyBeanName);
		}
		if(servletProxy == null){
			throw new ServletException("The servletProxy is null.");
		}else{
			return null;
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		if(servletProxy == null){
			chain.doFilter(request, response);
		}else{
			try {
				getServletProxy().service(req, res);
			} catch (Exception e) {
				LOGGER.error("Filter服务处理异常, 请求IP:{}, [URL:{}{}], 失败原因：{}",  IPUtils.parseIp(req), req.getRequestURL(), StringUtils.isNotEmpty(req.getQueryString()) ? ("?" + req.getQueryString()) : "",  e.getMessage(), e);
				res.setStatus(404);
			}
		}
	}
	

	@Override
	public void destroy() {
		
	}
}
